﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Login : System.Web.UI.Page
{
    Datautility DU = new Datautility();
    CommonLog Com = new CommonLog();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.Cookies["MyCookie"] != null)
        {
            TextBox pass = (TextBox)LoginUser.FindControl("Password");
            TextBox TxtCompanyName = (TextBox)LoginUser.FindControl("TxtCompanyName");
            pass.Attributes.Add("value", Request.Cookies["MyCookie"]["password"]);
            LoginUser.UserName = Request.Cookies["MyCookie"]["username"];
            TxtCompanyName.Text = Request.Cookies["MyCookie"]["TxtCompanyName"];
        }
    }
    protected void LoginUser_Authenticate(object sender, AuthenticateEventArgs e)
    {
        //Label LblMsg = (Label)LoginUser.FindControl("LblMsg");
        string ip = Request.ServerVariables["REMOTE_ADDR"];
        try
        {
            TextBox TxtCompanyName = (TextBox)LoginUser.FindControl("TxtCompanyName");
            CheckBox chBox = (CheckBox)LoginUser.FindControl("chBox");
            bool valid = false;
            DataSet ds = new DataSet();
            ds.ReadXml(Server.MapPath("~/App_Data/ConnStr.xml"));
            if (ds.Tables.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (ds.Tables[0].Rows[i]["companyname"].ToString() == TxtCompanyName.Text.Trim())
                    {
                        valid = true;
                        //Session["ConnStr"] = "Data Source=" + ds.Tables[0].Rows[i]["servername"].ToString() + ";Initial Catalog=" + ds.Tables[0].Rows[i]["dbname"].ToString() + ";user id=" + ds.Tables[0].Rows[i]["userid"].ToString() + ";password=" + ds.Tables[0].Rows[i]["password"].ToString() + ";Persist Security Info=False";
                        Session["ConnStr"] = "Data Source=" + ds.Tables[0].Rows[0]["servername"].ToString() + ";Initial Catalog=" + ds.Tables[0].Rows[0]["dbname"].ToString() + ";user id=" + ds.Tables[0].Rows[0]["userid"].ToString() + ";password=" + ds.Tables[0].Rows[0]["password"].ToString() + ";Persist Security Info=False";
                        break;
                    }
                }
            }
            if (valid == true)
            {
                SqlParameter[] param ={
                                 new SqlParameter("@username",LoginUser.UserName),
                                 new SqlParameter("@password",LoginUser.Password)
                             };
                DataTable DTUser = DU.getdatausingprocedure("usp_verify_user", param);
                if (DTUser.Rows.Count > 0)
                {
                    Session["username"] = DTUser.Rows[0]["username"].ToString();
                    Session["firstname"] = DTUser.Rows[0]["FirstName"].ToString();
                    Session["lastname"] = DTUser.Rows[0]["LastName"].ToString();
                    Session["groupid"] = DTUser.Rows[0]["GroupID"].ToString();
                    Session["isgroupactive"] = DTUser.Rows[0]["IsGroupActive"].ToString();
                    Session["userid"] = DTUser.Rows[0]["userid"].ToString();
                    //Session["compname"] = TxtCompanyName.Text.Trim();
                    Session["logintype"] = "0";
                    _BindSessionSettings();

                    DataTable dtcomp = DU.getdatausingprocedure("usp_get_acc_company_maintain_options");
                    if (dtcomp.Rows.Count > 0)
                    {
                        Session["compname"] = dtcomp.Rows[0]["CompName"].ToString();
                        Session["booksfromdate"] = dtcomp.Rows[0]["booksfromdate"].ToString();
                        Session["IsInvrEnabled"] = dtcomp.Rows[0]["IsInvrEnabled"].ToString();
                        Session["IsInvcEnabled"] = dtcomp.Rows[0]["IsInvcEnabled"].ToString();
                        Session["IsAccEnabled"] = dtcomp.Rows[0]["IsAccEnabled"].ToString();

                        string strSql = "SELECT * FROM ACC_USERWORKINGDATE WHERE USERID='" + DTUser.Rows[0]["userid"].ToString() + "'";
                        DataTable DTUserWoking = DU.getdata(strSql);
                        if (DTUserWoking.Rows.Count > 0)
                        {
                            string strCurrentDate = string.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(DTUserWoking.Rows[0]["WorkingDate"].ToString()));
                            Session["CURRENTDATE"] = strCurrentDate;
                            Session["FINYEAR"] = _GetFinancialYear(strCurrentDate);
                        }
                        else
                        {
                            if (dtcomp.Rows[0]["WorkingDate"].ToString() != string.Empty)
                            {
                                string strCurrentDate = string.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dtcomp.Rows[0]["WorkingDate"].ToString()));
                                Session["CURRENTDATE"] = strCurrentDate;
                                Session["FINYEAR"] = _GetFinancialYear(strCurrentDate);

                                SqlParameter[] sparam ={
                                                             new SqlParameter("@USERID",DTUser.Rows[0]["userid"].ToString()),
                                                             new SqlParameter("@WORKINGDATE",dtcomp.Rows[0]["WorkingDate"].ToString())
                                                            };
                                DU.executeprocedure("USP_ACC_SaveUserWorkingDate", sparam);
                            }
                        }
                    }
                    e.Authenticated = true;
                    if (chBox.Checked == true)
                    {
                        HttpCookie cookie1 = new HttpCookie("MyCookie");
                        cookie1.Values.Add("username", LoginUser.UserName);
                        cookie1.Values.Add("password", LoginUser.Password);
                        cookie1.Values.Add("TxtCompanyName", TxtCompanyName.Text);
                        cookie1.Expires = DateTime.Now.AddDays(1);//cookie Expires HttpContext.Current.Response.AppendCookie(cookie1);
                        Response.Cookies.Add(cookie1);
                    }
                    else
                    {

                    }                    
                    Com.SetLogs(Session["userid"].ToString(),Session["username"].ToString(), CommonLog.Type.ActivityLog.ToString(), "Successfull Login", "Login.aspx", ip, System.DateTime.Now.ToString());

                    //if(!String.IsNullOrEmpty(Request.QueryString["redirect"])) 
                    //{
                    //    string url =ResolveClientUrl(Request.QueryString["redirect"].ToString());
                    //    if(url=="PM")//for Manager
                    //    {
                    //        Response.Redirect("~/Main/Inventory/ViewPurchaseOrder.aspx");
                    //    }
                    //    else if(url=="PF")//forFinance
                    //    {
                    //        Response.Redirect("~/Main/Inventory/PurchaseOrderFinanceApprove.aspx");
                    //    }
                    //    else if (url == "PA") //for Admin
                    //    {
                    //        Response.Redirect("~/Main/Inventory/AdminPurchaseOrderApproval.aspx");
                    //    }
                    //}
                    //else
                    //{
                    //    Response.Redirect("Index.aspx");
                    //}
                    if (Request.QueryString["redirect"]!=null)
                    {
                        string url = ResolveClientUrl(Request.QueryString["redirect"].ToString());
                        Response.Redirect("Index.aspx?Check="+url);
                    }
                    else
                    {
                        Response.Redirect("Index.aspx");
                    }
                }
                else
                {
                    e.Authenticated = false;
                    //Com.SetLogs(Session["username"].ToString(), Session["userid"].ToString(), Common.Type.ActivityLog.ToString(), "Login Fail", "Login.aspx", ip, System.DateTime.Now.ToString());
                }
            }
            else
            {
                // LblMsg.Attributes.Add("class", "false");
                //LblMsg.Text = "Invalid company code!";
                
            }
        }
        catch (Exception ex)
        {
            //LblMsg.Text = ex.Message;
           // Com.SetLogs(Session["username"].ToString(), Session["userid"].ToString(), Common.Type.ActivityLog.ToString(), "Login Fail", "Login.aspx", ip, System.DateTime.Now.ToString());
        }
    }

    private string _GetFinancialYear(string strDate)
    {
        string strFinYear = string.Empty;
        if (strDate != string.Empty)
        {
            string[] str = strDate.Split('/');
            string strMonth = str[1];
            string strYear = str[2];
            if (Convert.ToInt32(strMonth) >= 04 && Convert.ToInt32(strMonth) <= 12)
            {
                strFinYear = strYear;
            }
            else if (Convert.ToInt32(strMonth) >= 1 && Convert.ToInt32(strMonth) < 4)
            {
                strFinYear = (Convert.ToInt32(strYear) - 1).ToString();
            }
        }
        return strFinYear;
    }

    private void _BindSessionSettings()
    {
        DataTable DT = DU.getdatausingprocedure("USP_ACC_GetAllAccountSettings");
        if (DT.Rows.Count > 0)
        {
            Session["LargeAmount"] = Convert.ToDouble(DT.Rows[0]["CHECKSTATUS"]).ToString();//SETTINGID 1
            Session["Negative"] = Convert.ToDouble(DT.Rows[1]["CHECKSTATUS"]).ToString();//SETTINGID 2
            Session["DateFormat"] = DT.Rows[2]["SETTINGVALUE"].ToString();//SETTINGID 3
            Session["DecimalPlace"] = DT.Rows[3]["SETTINGVALUE"].ToString();//SETTINGID 4
            Session["CurrencyName"] = DT.Rows[4]["SETTINGVALUE"].ToString();//SETTINGID 5
            Session["CurrencyDecimal"] = DT.Rows[5]["SETTINGVALUE"].ToString();//SETTINGID 6
            Session["CurrencySymbol"] = DT.Rows[6]["SETTINGVALUE"].ToString();//SETTINGID 7
            Session["AllowSubLedger"] = Convert.ToBoolean(DT.Rows[14]["CHECKSTATUS"]);//SETTINGID 15
            Session["EnableTDS"] = Convert.ToBoolean(DT.Rows[27]["CHECKSTATUS"]);//SETTINGID 28
            Session["TDSRoundOdd"] = DT.Rows[28]["SETTINGVALUE"].ToString();//SETTINGID 29
            Session["AvailST"] = Convert.ToBoolean(DT.Rows[29]["CHECKSTATUS"]);//SETTINGID 30
            Session["STCredit"] = DT.Rows[29]["SETTINGVALUE"].ToString();//SETTINGID 30
            Session["AllowCostCenter"] = Convert.ToBoolean(DT.Rows[30]["CHECKSTATUS"]);//SETTINGID 31
        }
    }

    protected void LoginUser_LoggedIn(object sender, EventArgs e)
    {
        //Response.Write("abc");
        //HttpCookie cookie1 = new HttpCookie("MyCookie");

        //cookie1.Values.Add("username", LoginUser.UserName);

        //cookie1.Values.Add("password", LoginUser.Password);

        //cookie1.Expires = DateTime.Now.AddDays(1);//cookie Expires HttpContext.Current.Response.AppendCookie(cookie1);
        //if ((Request.Browser.Cookies))
        //{
        //    //Check if the cookie with name PBLOGIN exist on user's machine
        //    if ((Request.Cookies["PBLOGIN"] == null))
        //    {
        //        //Create a cookie with expiry of 30 days
        //        Response.Cookies("PBLOGIN").Expires = DateTime.Now.AddDays(30);
        //        //Write username to the cookie
        //        Response.Cookies("PBLOGIN").Item("UNAME") = this.TbUserName.Text;
        //        //Write password to the cookie
        //        Response.Cookies("PBLOGIN").Item("UPASS") = this.TbPassword.Text;
        //    }
        //}
    }
}